//给todo案例创建模块 == 切片==slice==小仓库

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getTodolist } from "../../api/http";//引入接口

let initialState = { //管理的状态
    todolist: [
        { id: 1, title: 'xxx', sed: false },
        { id: 2, title: 'yyy', sed: false },
    ],
    n: 10
}

//1.使用createSlice创建slice切片 包含actions和reducer
const todosSlice = createSlice({
    name: "todos", //slice名称
    initialState,//管理的状态
    reducers: { //同步修改状态的方法

        addlist(state, action) { //添加
            state.todolist.push(action.payload)
        },
        dellist(state, action) { //删除
            state.todolist = state.todolist.filter(item => {
                return item.id !== action.payload
            })
        },
        clearsed(state, action) {//清除已完成
            state.todolist = state.todolist.filter(item => {
                return !item.sed
            })
        },
        changesed(state, action) { //状态切换的方法
            state.todolist.forEach(item => {
                if (item.id == action.payload) {
                    item.sed = !item.sed
                }
            })
        },
        getlist(state,action){ //获取 异步数据 payload=[]
            state.todolist = action.payload
        }
    },
});

//导出同步修改状态给 组件||异步 使用
export const { addlist, dellist, clearsed, changesed } = todosSlice.actions;
//导出reducer管理员函数 去创建store容器
export default todosSlice.reducer;

//异步方法:给组件的dispatch使用的
//异步方法中 先调取异步得到异步数据 再去执行同步修改

//获取列表数据的
export let async_getlist = createAsyncThunk('async_getlist',
     async(_,store) => {
    //先执行异步方法 得到异步数据
    let res = await getTodolist()
    //再去执行同步修改
    store.dispatch(getlist(res))
    
 })
